package cn.com.dashihui.api.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.log4j.Logger;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.json.FastJson;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.mysql.fabric.xmlrpc.base.Array;

import cn.com.dashihui.api.base.BaseService;
import cn.com.dashihui.api.common.GroupCode;
import cn.com.dashihui.api.common.OrderCode;
import cn.com.dashihui.api.common.PayCode;
import cn.com.dashihui.api.common.RedisKey;
import cn.com.dashihui.api.common.SysConfig;
import cn.com.dashihui.api.dao.Goods;
import cn.com.dashihui.api.dao.OrderG;
import cn.com.dashihui.api.dao.OrderGLog;
import cn.com.dashihui.api.dao.OrderPayAPIRecord;
import cn.com.dashihui.api.dao.User;
import cn.com.dashihui.api.radisysnc.inter.IGoodsBiz;
import cn.com.dashihui.api.radisysnc.inter.IRequest;
import cn.com.dashihui.api.radisysnc.inter.IRequestAsyncProcessBiz;
import cn.com.dashihui.api.radisysnc.inter.impl.ImplGoodsBiz;
import cn.com.dashihui.api.radisysnc.inter.impl.ImplRequestAsyncProcessBiz;
import cn.com.dashihui.api.radisysnc.request.InventoryQueryCacheRequest;
import cn.com.dashihui.api.radisysnc.request.InventoryUpdateDBRequest;
import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DoubleKit;
import cn.com.dashihui.pay.ZY.EncryUtils;
import cn.com.dashihui.pay.ZY.ZYPay;
import cn.com.dashihui.pay.wx.kit.HttpsRequest;
import cn.com.dashihui.pay.wx.kit.UtilKit;
import cn.com.dashihui.pay.wx.request.PreOrderReqData;
import cn.com.dashihui.pay.wx.request.QueryOrderReqData;
import cn.com.dashihui.pay.wx.request.RefOrderReqData;
import cn.com.dashihui.pay.wx.response.PreOrderResData;
import cn.com.dashihui.pay.wx.response.QueryOrderResData;
import cn.com.dashihui.pay.wx.response.RefOrderResData;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class GroupbuyingService  extends BaseService {
	private static Logger logger = Logger.getLogger(GroupbuyingService.class);
	private IGoodsBiz goodsBiz = new ImplGoodsBiz();
	private	IRequestAsyncProcessBiz  requestAsyncProcessBiz = new ImplRequestAsyncProcessBiz();
	//使用Duang.duang进行封装，使普通类具有事务的功能
	private OrderService orderservice = Duang.duang(OrderService.class);
	private Cache teamCache = Redis.use();
	
	
	public void demo() {
		
	}
	
	/**
	 * 
	*<p>Title: updateDBGoods</p> 
	*<p>Description: 提交更新请求,放入队列</p> 
	　 * @param Goods
	　 * @return
	 */
	public void updateDBGoods(Goods goods){
        IRequest request = new InventoryUpdateDBRequest(goods,goodsBiz);
        request.process();
//        requestAsyncProcessBiz.process(request);
    }
	/**
	 * 
	*<p>Title: updateDBOrderG</p> 
	*<p>Description: 提交更新请求,放入队列</p> 
	　 * @param OrderG
	　 * @return
	 */
	public void updateDBOrderG(OrderG order){
        IRequest request = new InventoryUpdateDBRequest(order,goodsBiz);
        request.processOrderG();
    }
	
	/**
	*<p>Title: queryGoods</p> 
	*<p>Description: 描述：提交查询请求
	*  1、先从缓存中取数据
	*  2、如果能从缓存中取到数据，则返回
	*  3、如果不能从缓存取到数据，则等待20毫秒，然后再次去数据，直到200毫秒，如果超过200毫秒还不能取到数据，则从数据库中取，并强制刷新缓存数据 </p> 
	* @param goodsId
	* @return
	*/
	public Goods queryGoods(Integer goodsId) {
        IRequest request = new InventoryQueryCacheRequest(goodsId,goodsBiz,false);
        requestAsyncProcessBiz.process(request);//加入到队列中
        long startTime = System.currentTimeMillis();
        long allTime = 0L;
        long endTime = 0L;
        Goods goods = null;
        while (true) {
            if (allTime > 200){//如果超过了200ms,那就直接退出，然后从数据库中查询
                break;
            }
            try {
                goods = goodsBiz.loadGoodsCache(goodsId);
                if (goods != null) {
                	System.out.println("取出来了~~~~~~~~~~~~");
                    return goods;
                } else {
                    Thread.sleep(20);//如果查询不到就等20毫秒
                } 
                endTime = System.currentTimeMillis();
                allTime = endTime - startTime;
            } catch (Exception e) {
            } 
        }
        /**
         * 代码执行到这来，只有以下三种情况
         * 1、缓存中本来有数据，由于redis内存满了，redis通过LRU算法清除了缓存，导致数据没有了
         * 2、由于之前数据库查询比较慢或者内存太小处理不过来队列中的数据，导致队列里挤压了很多的数据，所以一直没有从数据库中获取数据然后插入到缓存中
         * 3、数据库中根本没有这样的数据，这种情况叫数据穿透，一旦别人知道这个商品没有，如果一直执行查询，就会一直查询数据库，如果过多，那么有可能会导致数据库瘫痪
         */
        goods = goodsBiz.loadGoodsByGoodsId(goodsId);
        System.out.println("超时了~~~~~~~~~~~~:"+goods);
        if (goods != null) {
            IRequest forcRrequest = new InventoryQueryCacheRequest(goodsId,goodsBiz,true);
            forcRrequest.process();//这个时候需要强制刷新数据库，使缓存中有数据
            return goods;
        }
        return null;
        
    }
	/**
	*<p>Title: queryGoods</p> 
	*<p>Description: 描述：提交查询请求
	*  1、先从缓存中取数据
	*  2、如果能从缓存中取到数据，则返回
	*  3、如果不能从缓存取到数据，则等待20毫秒，然后再次去数据，直到200毫秒，如果超过200毫秒还不能取到数据，则从数据库中取，并强制刷新缓存数据 </p> 
	* @param goodsId
	* @return
	*/
	public OrderG queryOrderG(String orderNum) {
        IRequest request = new InventoryQueryCacheRequest(orderNum,goodsBiz,false);
        requestAsyncProcessBiz.processOrderG(request);//加入到队列中
        long startTime = System.currentTimeMillis();
        long allTime = 0L;
        long endTime = 0L;
        OrderG order = null;
        while (true) {
            if (allTime > 200){//如果超过了200ms,那就直接退出，然后从数据库中查询
                break;
            }
            try {
                order = goodsBiz.loadOrderGCache(orderNum);
                if (order != null) {
                	System.out.println("取出来了~~~~~~~~~~~~");
                    return order;
                } else {
                    Thread.sleep(20);//如果查询不到就等20毫秒
                } 
                endTime = System.currentTimeMillis();
                allTime = endTime - startTime;
            } catch (Exception e) {
            } 
        }
        /**
         * 代码执行到这来，只有以下三种情况
         * 1、缓存中本来有数据，由于redis内存满了，redis通过LRU算法清除了缓存，导致数据没有了
         * 2、由于之前数据库查询比较慢或者内存太小处理不过来队列中的数据，导致队列里挤压了很多的数据，所以一直没有从数据库中获取数据然后插入到缓存中
         * 3、数据库中根本没有这样的数据，这种情况叫数据穿透，一旦别人知道这个商品没有，如果一直执行查询，就会一直查询数据库，如果过多，那么有可能会导致数据库瘫痪
         */
        order = goodsBiz.loadOrderG(orderNum);
        System.out.println("超时了~~~~~~~~~~~~:"+order);
        if (order != null) {
            IRequest forcRrequest = new InventoryQueryCacheRequest(orderNum,goodsBiz,true);
            forcRrequest.process();//这个时候需要强制刷新数据库，使缓存中有数据
            return order;
        }
        return null;
        
    }

	/**
	 * 查询商品信息
	 * @param storeid 店铺ID
	 *
	 */
	public Record findDetail(int goodsid){
		String sql = "SELECT tg.id,tg.Qrthumb,tg.name,tg.sellPrice,tg.buytype,tg.buycount,tg.shiyongren,tg.regul,tg.shortInfo,"
				+ "tg.zspointnum,tg.zsdedunum,tg.zscouponnum,tg.zsactivity,tg.browse,tg.gbmethod,tg.gbfreeperson,tg.gbpayperson, "
				+ "tg.thumb,tg.state,tg.countnum,tg.describe,tg.LunBoNum,tg.groupbuying,tg.gbperson,tg.gbprice,tg.gbbegintime,tg.gbendtime, "
				+ "0 isCollected,"
				+ "(SELECT COUNT(*) FROM t_bus_order_gb bo WHERE bo.goodsid=? AND bo.payState=?) saleCount,"
				+ "(SELECT COUNT(*) FROM t_bus_user_collection buc WHERE buc.goodsid=? AND buc.isCancel=0) collectedCount "
				+ " FROM t_bus_goods tg "
				+ " WHERE  tg.id=? ";
		return Db.findFirst(sql,goodsid,OrderCode.OrderState.FINISH,goodsid,goodsid);
	}
	/**
	 * 查询商品信息，并且查询该商品是否被当前登录用户收藏
	 * @param userid 当前登录用户ID
	 * 
	 * @param goodsid 商品ID
	 */
	public Record findDetail(int userid,int goodsid){
		String sql = "SELECT tg.id,tg.Qrthumb,tg.name,tg.sellPrice,tg.buytype,tg.buycount,tg.shiyongren,tg.regul,tg.shortInfo,"
				+ "tg.zspointnum,tg.zsdedunum,tg.zscouponnum,tg.zsactivity,tg.browse,tg.gbmethod,tg.gbfreeperson,tg.gbpayperson, "
				+ "tg.thumb,tg.state,tg.countnum,tg.describe,tg.LunBoNum,tg.groupbuying,tg.gbperson,tg.gbprice,tg.gbbegintime,tg.gbendtime, "
				+ "(SELECT COUNT(*) FROM t_bus_user_collection buc WHERE buc.userid=? AND buc.goodsid=? AND buc.isCancel=0)!=0 isCollected,"
				+ "(SELECT COUNT(*) FROM t_bus_order_gb bo WHERE bo.goodsid=? AND bo.payState=?) saleCount,"
				+ "(SELECT COUNT(*) FROM t_bus_user_collection buc WHERE buc.goodsid=? AND buc.isCancel=0) collectedCount "
				+ " FROM t_bus_goods tg "
				+ " WHERE  tg.id=? ";
		return Db.findFirst(sql,userid,goodsid,OrderCode.OrderState.FINISH,goodsid,goodsid);
	}

	/**
	 * 保存订单
	 * @param order
	 * @throws Exception 
	 * @return 1 邮费异常 2 商品已下架 3库存不足 4 不具有开团资格  5 团长订单未支付 6价格问题  7 每天限购  8 团购结束  
	 */
	@Before(Tx.class)
	public int save(OrderG order,String isRedeem,User user) throws Exception {
	
		/**
		 * 验证用户要购买的自营商品
		 * 1.验证是否有商品已下架
		 * 2.验证是否有商品购买量已经超过了今日所限量
		 * 3.验证总金额是否与客户端的入参总金额相同
		 */
		//准备数据
		//邮费
		Double postAge = 0.00;
		Double postAgeFree = 0.00;
		//限购配制
		int maxBuy = 0;
		try {
			postAge = SysConfig.getPostAge();
			postAgeFree = SysConfig.getPostAgeFree();
			maxBuy = (int)SysConfig.getGroupMaxBuy();
		} catch (Exception e) {
			return 1;
		}
		//从缓存取出
		Goods good = Goods.me().findById(order.getStr("goodsid"));
//		Goods good = queryGoods(Integer.parseInt(order.getStr("goodsid")));
		if(good==null){
			throw new Exception("取出Goods失败");
		}
		//1.验证是否商品已下架
		System.out.println("66666666666666"+good);
		if(good.getInt("state")!=2){
			return 2;
		}
		//2.验证库存  
		if(good.getInt("countnum")<1){

			return 3;
		}
		
		
		
		//3.验证限购
		String sql = "SELECT A.* FROM ( "
				+ " SELECT g.id,DATE_FORMAT(g.payDate,'%Y-%m-%d') as paytime "
				+ " FROM t_bus_order_gb g WHERE g.userid=? AND g.goodsid=? AND g.payState=? "
				+ " ) as A WHERE  A.paytime=? ";
		String Day = DatetimeKit.getFormatDate("yyyy-MM-dd");
		List<Record> lists = Db.find(sql,user.getInt("id"),order.getStr("goodsid"),
				OrderCode.OrderPayState.HAD_PAY,Day);
//		if( lists!=null ){
//			if (lists.size()==maxBuy || lists.size()>maxBuy ){
//				return 7;
//			}
//		}
		//验证团购是否过期
		Date date = good.getDate("gbendtime");
		if (DatetimeKit.compareDate(date)<0 || DatetimeKit.compareDate(date)==0 ) {
			return 8;	
		}
		//团购订单日志
		OrderGLog log = new OrderGLog();
		Double amount = order.getDouble("amount");
		Double price = 0.00;
		
		Double miniNumMoney=SysConfig.getMiniNumMoney();
		boolean flag = false;
		if(price.compareTo(miniNumMoney) == 0){
			flag = true;
		}
		if("0".equals(isRedeem)){
			
			//查询是否需要开团   
			List<Record> find = Db.find("SELECT id FROM t_bus_order_gb WHERE goodsid=? AND buyNum=1 ", good.getInt("id"));
			if(find.size()==0||find==null){
//				if(!flag){
					//需要   查询是否具有开团资格
					if(user.getInt("createteam")!=1){
						return 4;
					}
//				}
			}
			//单独购买价格
			price = good.getDouble("sellPrice");
			order.set("buyType", GroupCode.buytype.ALONE);
		}else{
			/**如果是拼单，查询是否需要开团   
			 * 	1. 需要开团，查询是否具有开团资格
			 *  2. 无需开团
			 */
			if("1".equals(isRedeem)){
				//查询是否需要开团   
				List<Record> find = Db.find("SELECT id FROM t_bus_order_gb WHERE goodsid=? AND buyNum=1 ", good.getInt("id"));
				if(find.size()==0||find==null){
//					if(!flag){
						//需要   查询是否具有开团资格
						if(user.getInt("createteam")!=1){
							return 4;
						}
//					}
				}
				
			}else if("2".equals(isRedeem)){
				//验证是否具有开团中团资格(是否团中团团长，团中团号)
				//需要   查询是否具有开团资格
//				if(!flag){
					if(user.getInt("createteam")!=1){
						return 4;
					}
//				}
				order.set("isLeader", GroupCode.isLeader.LEADER);
				//生成团中团编号
				String  teamNum = DatetimeKit.getFormatDate("yyyyMMddHHmmss")+user.getInt("id");
				order.set("teamNum", teamNum);
			}else if("3".equals(isRedeem)){
				Record rec = Db.findFirst("SELECT id FROM t_bus_order_gb WHERE teamNum=? AND payState=? ",order.getStr("teamNum"),OrderCode.OrderPayState.HAD_PAY);
				if(rec == null){
					//团长订单未支付
					return 5;
				}
				//加入团中团
				order.set("isLeader", GroupCode.isLeader.NOTLEADER);
			}
			//团购价格
			price = good.getDouble("gbprice");
			order.set("buyType",  GroupCode.buytype.TEAM);
		}
		//是否包邮
		if(price.compareTo(postAgeFree)==-1){
			price = DoubleKit.add(price, postAge);
		}
		order.set("gbperson", good.getInt("gbperson"))	//团购人数
			.set("gbprice",good.getDouble("gbprice"))	
			.set("gbbegintime", good.getDate("gbbegintime"))
			.set("gbendtime",good.getDate("gbendtime"))	
			.set("gbmethod", good.getInt("gbmethod"))
			.set("gbfreeperson", good.getInt("gbfreeperson"))
			.set("gbpayperson",good.getInt("gbpayperson"));	
		//验证金额
		System.out.println("*"+price+"*");
		System.out.println("*"+amount+"*");
		if(Double.compare(price, amount)!=0){
			return 6;
		}
		
		Record add = Db.findById("t_bus_user_address", order.get("addressid"));
		if(add == null){
			return 9;
		}
		order.set("receivename", add.get("linkname"))
		.set("receiveaddress", add.get("address"));
		//保存订单
		if(!order.save()){
			throw new Exception("生成订单失败");
		}
		//t_bus_order_list表
		makelist(order, user, good, amount);
		//减库存，操作数据库
		int goodsid = good.getInt("id");
		goodsBiz.removeGoodsCache(goodsid);
		
		//减库存
		int count = downStock(good, goodsid);
		if ( count == 3){
			return 3;
		}
		
		//记录日志
		log.set("orderNum", order.get("orderNum"))
			.set("type", OrderCode.OrderLogType.SAVE)
			.set("user", order.get("userid"))
			.set("action", OrderCode.OrderLogType.SAVE_ACTION)
			.set("content", OrderCode.OrderLogType.SAVE_CONTECT);
		if(!log.save()){
			throw new Exception("日志记录失败");
		}
		
		return 0;
	}

	private void makelist(OrderG order, User user, Goods good, Double amount) {
		//批量保存商品列表
		Object[][] params = new Object[1][24];
		String sqls = "INSERT INTO t_bus_order_list(goodsid,orderNum,name,price,thumb,count,amount,sellerId,"
				+ "isToker,onePoint,oneDetion,oneDcount,twoPoint,twoDetion,twoDcount,threePoint,threeDetion,"
				+ "threeDcount,fourPoint,fourDetion,fourDcount,fivePoint,fiveDetion,fiveDcount) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		//根据ids查询拓客
		Record toker = Db.findFirst("SELECT tt.* FROM t_bus_goods_toker tt WHERE tt.state=1 AND tt.goodsId=?",order.getStr("goodsid"));
		
		params[0][0]=order.getStr("goodsid");
		params[0][1]=order.getStr("orderNum");
		params[0][2]=good.getStr("name");
		params[0][3]=amount;
		params[0][4]=good.getStr("thumb");
		params[0][5]=1;
		params[0][6]=amount;
		params[0][7]=user.getInt("toBossThreeId");;
		if(toker!=null){
			params[0][8]=1;
			params[0][9]=toker.getDouble("onePoint");
			params[0][10]=toker.getDouble("oneDetion");
			params[0][11]=toker.getDouble("oneDcount");
			params[0][12]=toker.getDouble("twoPoint");
			params[0][13]=toker.getDouble("twoDetion");
			params[0][14]=toker.getDouble("twoDcount");
			params[0][15]=toker.getDouble("threePoint");
			params[0][16]=toker.getDouble("threeDetion");
			params[0][17]=toker.getDouble("threeDcount");
			params[0][18]=toker.getDouble("fourPoint");
			params[0][19]=toker.getDouble("fourDetion");
			params[0][20]=toker.getDouble("fourDcount");
			params[0][21]=toker.getDouble("fivePoint");
			params[0][22]=toker.getDouble("fiveDetion");
			params[0][23]=toker.getDouble("fiveDcount");
		}else{
			params[0][8]=0;
			params[0][9]=0;
			params[0][10]=0;
			params[0][11]=0;
			params[0][12]=0;
			params[0][13]=0;
			params[0][14]=0;
			params[0][15]=0;
			params[0][16]=0;
			params[0][17]=0;
			params[0][18]=0;
			params[0][19]=0;
			params[0][20]=0;
			params[0][21]=0;
			params[0][22]=0;
			params[0][23]=0;
		}
		Db.batch(sqls, params, 1);
	}
	/**
	 *    库存的   版本控制   防止 并发下操作库存
	 * @param good
	 * @param goodsid
	 * @return
	 */
	private int downStock(Goods good, int goodsid) {
		//旧库存
		int oldStock =  good.getInt("countnum");
		System.out.println(good.getInt("countnum")-1);
		int count = Db.update("UPDATE t_bus_goods SET countnum = ? WHERE id=? AND countnum=? ",oldStock-1,goodsid,oldStock);
		if ( count == 1) {
			//操作成功
			goodsBiz.removeGoodsCache(goodsid);
			return 0;
		} else {
			good =  Goods.me().findById(goodsid);
			//2.再次验证库存  
			if(good.getInt("countnum")<1){
				return 3;
			}
			return downStock( good,  goodsid);
		}
	}

	/**
	 * 支付预处理
	 * @param orderNum
	 * @param flagStr
	 * @param token
	 * @param user
	 * @return 1 订单不存在  2 订单已过期
	 * @throws Exception 
	 */
	@Before(Tx.class)
	public String pay(String orderNum,String flagStr,String token,User user,String ip,String isPC) throws Exception {
//		String str = orderNum.subSequence(0, 1).toString();
		//查询订单是否存在
		OrderG order = OrderG.me().findFirst("SELECT * FROM t_bus_order_gb WHERE orderNum = ? AND payState=? ", orderNum,OrderCode.OrderPayState.NO_PAY);
		if(order==null){
			throw new Exception("订单不存在");
		}
		//验证订单是否有效
		if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
			throw new Exception("订单与已过期");
		}
		//验证团购是否过期
		Date date = order.getDate("gbendtime");
		if (DatetimeKit.compareDate(date) == -1 || DatetimeKit.compareDate(date)==0 ) {
			throw new Exception("团购已过期");
		}
		
		
		//订单总金额
		Double amount = order.getDouble("amount");
		//根据支付方式不同做不同处理
		Integer payMethod = Integer.parseInt(flagStr);
		System.out.println("付款方式:"+payMethod);
		if(payMethod == OrderCode.OrderPayMethod.WEIXIN){
			//1：微信支付
			String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
			String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
			
			//获取订单总金额，并转换为以“分”为单位
			String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
			
			//向微信发起预支付请求
			PreOrderReqData preOrderReqData = new PreOrderReqData("亿品直供",orderNum,amountStr,ip,PropKit.get("weixinpay.goodsOrderNotifyUrl"),startDate,expireDate);
			PreOrderResData preOrderRspData = null;
			try {
				preOrderRspData = (PreOrderResData)UtilKit.getObjectFromXML(new HttpsRequest().post(PropKit.get("weixinpay.unifiedorder"), preOrderReqData), PreOrderResData.class);
			}catch(Exception e){
				throw new Exception("支付请求异常");
			}
			//预支付完成
			if(preOrderRspData!=null){
				System.out.println("Response....:"+preOrderReqData);
				//保存接口请求记录
				String sendContent = UtilKit.getXMLFromObject(preOrderReqData);
				String returnContent = UtilKit.getXMLFromObject(preOrderRspData);
				new OrderPayAPIRecord().set("orderNum", orderNum)
					.set("sendContent", sendContent)
					.set("returnContent", returnContent)
					.set("payMethod", payMethod)
					.set("flag", 1)
					.save();
				if(preOrderRspData.getReturn_code().equals("SUCCESS")&&preOrderRspData.getResult_code().equals("SUCCESS")){
					//更新订单支付方式为微信
					order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
					//向客户端返回结果
					String url = PropKit.get("weixinpay.redirect_url");
					try {
						url = URLEncoder.encode(url, "GBK");
					} catch (UnsupportedEncodingException e) {
						throw new Exception("编码转换错误");
					}
					url = preOrderRspData.getMweb_url()+ "&redirect_url=" +url + "?ORDERNUM="+orderNum ;
					return url;
				}else{
					throw new Exception("支付失败");
				}
			}else{
				throw new Exception("支付请求失败");
			}
		}else if(payMethod == OrderCode.OrderPayMethod.ALIPAY){
			System.out.println("H5进入支付宝支付");
			//2：支付宝支付
			//获取订单总金额，并转换为以“元”为单位
			String amountStr1 = String.valueOf(Double.valueOf(amount)).toString();
			String gateway=PropKit.get("applipay.url");
			String app_id=PropKit.get("appalipay.partner");
			String privateKey=PropKit.get("appalipay.privateKey");
			String alipayPublicKey=PropKit.get("appalipay.alipayPublicKey");
			String charset=PropKit.get("applipay.charset");
			String sign_type=PropKit.get("applipay.signType");
			String app_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.appCertPublicKey");
			String alipay_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayCertPublicKey");
			String alipay_root_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayRootCert");
			String alipay_notify_url =PropKit.get("appalipay.goodsOrderNotifyUrl");
			String alipay_return_url =PropKit.get("appalipay.returnUrl");
			
			//构造client
			CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
			//设置网关地址
			certAlipayRequest.setServerUrl(gateway);
			//设置应用Id
			certAlipayRequest.setAppId(app_id);
			//设置应用私钥
			certAlipayRequest.setPrivateKey(privateKey);
			//设置请求格式，固定值json
			certAlipayRequest.setFormat("json");
			//设置字符集
			certAlipayRequest.setCharset(charset);
			//设置签名类型
			certAlipayRequest.setSignType(sign_type);
			//设置应用公钥证书路径
			certAlipayRequest.setCertPath(app_cert_path);
			//设置支付宝公钥证书路径
			certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
			//设置支付宝根证书路径
			certAlipayRequest.setRootCertPath(alipay_root_cert_path);
			
			
			
			
			AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
			model.setOutTradeNo(orderNum);
			model.setTotalAmount(amountStr1);
			model.setSubject("亿拼惠团购");
			model.setProductCode("QUICK_WAP_WAY");
			
			AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
			alipayRequest.setBizModel(model);
			alipayRequest.setNotifyUrl(alipay_notify_url);
			alipayRequest.setReturnUrl(alipay_return_url);
			
			DefaultAlipayClient alipayClient;
			try {
				alipayClient = new DefaultAlipayClient(certAlipayRequest);
				AlipayTradeWapPayResponse response= alipayClient.pageExecute(alipayRequest);
				new OrderPayAPIRecord().set("orderNum", orderNum)
				.set("sendContent", alipayRequest.getBizModel().toString())
				.set("returnContent", response.getBody())
				.set("payMethod", payMethod)
				.set("flag", 1)
				.save();
				//更新订单支付方式为支付宝
				order.set("paytype", OrderCode.OrderPayMethod.ALIPAY).update();
				//将结果返回给客户端
				return response.getBody();
				
			} catch (AlipayApiException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new Exception("支付失败");
			}
			
		}else if(payMethod == OrderCode.OrderPayMethod.BALANCE){
			//郑大支付
			//将订单改为余额支付
			//更新订单支付方式为余额
			if(!order.set("paytype", OrderCode.OrderPayMethod.BALANCE).update()){
				throw new Exception("更改订单支付类型失败");
			}
			//查询用户余额  判断是否充足
			Map<String,String> map = new HashMap<String,String>();
			map.put("token", token);
			JSONObject js = ZYPay.find(map);
			Map<String, Object> resMap =EncryUtils.toMap(js);
			if("000000".equals(resMap.get("result"))){
	    		//查询成功
				JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
				JSONArray array = JSONArray.fromObject(jsondata.get("DATA"));
				jsondata = JSONObject.fromObject(array.get(0));
				if(orderservice.saveMoneyUp(jsondata.getDouble("SUMMONEY"),user.getInt("id"))!=1){
					throw new Exception("更新余额失败");
				}
	    		//账户余额
				Double money = jsondata.getDouble("SUMMONEY");
				if(Double.compare(money, amount)==-1){
					throw new Exception("余额不足");
				}
				//支付
				Map<String,String> map1 = new HashMap<String,String>();
				String orderid = "Z"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(4);
				map1.put("order_type", PayCode.ORDERTYPE.MONEYPAY);//下单类型 2在线支付
				map1.put("order_id", orderid);
				map1.put("pay_firmid", user.get("payid")+"");
				map1.put("pay_firmname", user.getStr("name"));
				map1.put("pay_phone", user.getStr("phone"));
				
				map1.put("terminal_type", isPC);
				if("1".equals(isPC)){
					map1.put("terminal_num","MAC");
				}else if("2".equals(isPC)){
					map1.put("terminal_num","IMEI");
				}else{
					map1.put("terminal_num","OTHER");
				}
				map1.put("order_ip", ip);
				String money1 = new DecimalFormat("0.00").format(amount);
				map1.put("order_money",money1);
				Double orderfree =0.00;
				String format = new DecimalFormat("0.00").format(orderfree);
				map1.put("order_fee",format);
				map1.put("token",token);
				JSONObject jss = null;
				try {
					jss =ZYPay.createOrder(map1);
				} catch (Exception e) {
					throw new Exception("Base64转换失败");
				}
				Map<String, Object> resMap1 =EncryUtils.toMap(jss);
				if("000000".equals(resMap1.get("result"))){
		    		//支付
					JSONObject jsondata1 = JSONObject.fromObject(resMap1.get("data"));
					if(Db.findFirst("SELECT * FROM t_bus_user_pay_orderid WHERE ischeck=1 AND fromOrderNum=?",orderNum)!=null){
						throw new Exception("订单重复提交");
					}
					//创建订单表
					Record re = new Record().set("orderid",orderid)
											.set("fromOrderNum", orderNum)
											.set("userid", user.getInt("id"))
											.set("type", 1)
											.set("ischeck", 0)
											.set("money", money1)
											.set("moneyfree", format)
											.set("createDate", new Date());
					if(!Db.save("t_bus_user_pay_orderid", re)){
						throw new Exception("保存支付表失败");
					}
					System.out.println(">>>>>>>>>>>>>>>"+jsondata1.get("location_url"));
		    		return (String) jsondata1.get("location_url");
		    	}else{
		    		//支付失败
		    		throw new  Exception((String)resMap1.get("msg"));
		    	}
	    	}else{
	    		//查询余额失败
	    		throw new Exception("查询余额失败");
	    	}
		}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
			//更新订单支付方式为余额
			order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
			//查询用户余额  判断是否充足
			Double money = user.getDouble("money");
			if(Double.compare(money, amount)==-1){
				//余额不足
				throw new Exception("余额不足");
			}
			//支付
			int userid = user.getInt("id");
			//变化前金额
			Double oldMoney = user.getDouble("money");
			//增加的金额
			Double addMoney = amount;
			//变化后金额
			Double newMoney = DoubleKit.sub(oldMoney, addMoney);
			
			Record re = new Record().set("userid", userid)
					.set("amount", amount)
					.set("type", "2")
					.set("fromOrderNum", orderNum)
					.set("createDate", new Date())
					.set("orderType", OrderCode.MoneyState.GOODORDER)
					.set("nowAmount", newMoney)
					.set("oldAmount", oldMoney)
					.set("describe", "购买团购商品");
			if(Db.update("UPDATE t_bus_user SET money = ? WHERE id = ?", newMoney,userid)==1){
				if(Db.save("t_bus_user_money", re)){
					if (order.set("orderState", OrderCode.OrderPayState.HAD_PAY).set("payState", OrderCode.OrderPayState.HAD_PAY).set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).update()) {
						if(Db.update("INSERT INTO t_bus_order_log(orderNum,type,user,action,content) VALUES(?,?,?,?,?)",orderNum,OrderCode.OrderLogType.PAY,"用户",OrderCode.OrderLogType.PAY_ACTION,"订单支付成功，等待系统确认")==1){
							return "SUCCESS";
						}
						throw new Exception("订单日志记录失败");
					}
					throw new RuntimeException("更改订单状态失败"); 
				}
				throw new RuntimeException("记录money变化表失败"); 
			}
			throw new RuntimeException("更改用户余额失败");
				
	    	
	    	
		}else{
			throw new Exception("没有该支付方式");
		}
	}

	/**
	 * 查询支付结果
	 * @param user
	 * @param orderNum
	 * @param token
	 * @throws Exception 
	 */
	@Before(Tx.class)
	public int query(User user, String orderNum, String token) throws Exception {
		//从缓存查询订单
		OrderG order = OrderG.me().findFirst("SELECT * FROM t_bus_order_gb WHERE orderNum = ? AND userid=?", orderNum,user.getInt("id"));
		if(order==null){
			throw new Exception("订单不存在");
		}
		//查询支付状态
		//依次判断订单支付状态
		if(order.getInt("payState")==OrderCode.OrderPayState.NO_PAY){
			
			//如果状态为未支付，则调用相应支付平台的接口进行再次验证
			if(order.getInt("paytype")==OrderCode.OrderPayMethod.WEIXIN){
				//1：微信支付
				try {
					QueryOrderReqData queryOrderReqData = new QueryOrderReqData(orderNum);
					String responseStr = new HttpsRequest().post(PropKit.get("weixinpay.orderquery"), queryOrderReqData);
					QueryOrderResData queryOrderResData = (QueryOrderResData) UtilKit.getObjectFromXML(responseStr, QueryOrderResData.class);
					if(queryOrderResData!=null){
						//保存接口请求记录
						new OrderPayAPIRecord().set("orderNum", orderNum)
						.set("sendContent", UtilKit.getXMLFromObject(queryOrderReqData))
						.set("returnContent", UtilKit.getXMLFromObject(queryOrderResData))
						.set("payMethod", OrderCode.OrderPayMethod.WEIXIN)
						.set("flag", 3)
						.save();
						if(queryOrderResData.getReturn_code().equals("SUCCESS")&&queryOrderResData.getResult_code().equals("SUCCESS")&&queryOrderResData.getTrade_state().equals("SUCCESS")){
							// 微信订单状态的更改  积分等券的发放
							//根据订单号和用户id更改order表的订单状态
							
							order.set("paytype", OrderCode.OrderPayTypes.WEIXIN)
								.set("payState", OrderCode.OrderPayState.HAD_PAY)
								.set("orderState",  OrderCode.OrderLogType.PAY)
								.set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
							if(!order.update()){
								throw new Exception("更改订单失败");
							}
							//根据订单号和用户id记录订单日志
							OrderGLog log = new OrderGLog();
							log.set("orderNum", orderNum)
								.set("type", OrderCode.OrderLogType.PAY)
								.set("user", order.get("userid"))
								.set("action", OrderCode.OrderLogType.PAY_ACTION_WEIXIN)
								.set("content", OrderCode.OrderLogType.PAY_CONTECT);
							if(!log.save()){
								throw new Exception("日志记录失败");
							}
							orderGMoneyStateUpdateAndGive(order,user,1,"购买商品");
							//查询订单表有没有该商品， 分辨是否开团， 是否是团长      团队序号    
							new GroupbuyingService2().dealTeamBuy(order);
							
//							order = dealTeamOrder(order);  //TODO
//							if(!order.update()){
//								throw new Exception("更改订单失败");
//							}
							return 1;
						}else{
				    		return 2;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if(order.getInt("paytype")==OrderCode.OrderPayMethod.BALANCE){
				//根据orderNum 查找order 
				List<Record> res = orderservice.queryOrderByOrderNum(orderNum);
				if(res==null|| res.size()<=0){
					throw new Exception("没有该笔订单");
				}
				for(Record re : res){
					Map<String,String> map = new HashMap<String,String>();
					map.put("order_id", re.getStr("orderid"));
					System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>订单号"+re.getStr("orderid"));
					map.put("token", token);
					JSONObject js = ZYPay.orderstate(map);
					Map<String, Object> resMap =EncryUtils.toMap(js);
					if("000000".equals(resMap.get("result"))){
			    		//查询成功
						JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
						if(jsondata.get("order_type").equals("2")&&jsondata.get("order_status").equals("S")){
							// 1 成功  2 更改订单失败 3 用户券信息更新失败  4 减少库存失败 5记录日志失败  7 更改用户等级失败  8 记录等级变更失败
							
							//根据订单号和用户id更改order表的订单状态
							order.set("paytype", OrderCode.OrderPayTypes.BALANCE)
								.set("payState", OrderCode.OrderPayState.HAD_PAY)
								.set("orderState",  OrderCode.OrderLogType.PAY)
								.set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
							if(!order.update()){
								throw new Exception("更改订单失败");
							}
							//根据订单号和用户id记录订单日志
							OrderGLog log = new OrderGLog();
							log.set("orderNum", orderNum)
								.set("type", OrderCode.OrderLogType.PAY)
								.set("user", order.get("userid"))
								.set("action", OrderCode.OrderLogType.PAY_ACTION)
								.set("content", OrderCode.OrderLogType.PAY_CONTECT);
							if(!log.save()){
								throw new Exception("日志记录失败");
							}
							orderGMoneyStateUpdateAndGive(order,user,1,"购买商品");
							new GroupbuyingService2().dealTeamBuy(order);
							//查询订单表有没有该商品， 分辨是否开团， 是否是团长      团队序号         
//							order = dealTeamOrder(order); //TODO
							return 1;
						}
			    	}
				}
			}else if (order.getInt("paytype")==OrderCode.OrderPayMethod.ALIPAY) {
				//支付宝
				String gateway=PropKit.get("applipay.url");
				String app_id=PropKit.get("appalipay.partner");
				String privateKey=PropKit.get("appalipay.privateKey");
				String alipayPublicKey=PropKit.get("appalipay.alipayPublicKey");
				String charset=PropKit.get("applipay.charset");
				String sign_type=PropKit.get("applipay.signType");
				String app_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.appCertPublicKey");
				String alipay_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayCertPublicKey");
				String alipay_root_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayRootCert");
				String alipay_notify_url =PropKit.get("appalipay.goodsOrderNotifyUrl");
				//构造client
				CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
				certAlipayRequest.setServerUrl(gateway);
				certAlipayRequest.setAppId(app_id);
				certAlipayRequest.setPrivateKey(privateKey);
				certAlipayRequest.setFormat("json");
				certAlipayRequest.setCharset(charset);
				certAlipayRequest.setSignType(sign_type);
				certAlipayRequest.setCertPath(app_cert_path);
				certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
				certAlipayRequest.setRootCertPath(alipay_root_cert_path);
				AlipayClient alipayClient;
				try {
					alipayClient = new DefaultAlipayClient(certAlipayRequest);
					AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
					request.setBizContent("{" +
					"   \"out_trade_no\":\""
					+ orderNum
					+ "\"" +
					"  }");//设置业务参数
					AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);//通过alipayClient调用API，获得对应的response类
					System.out.println(response.getBody());
					//保存接口请求记录
					new OrderPayAPIRecord().set("orderNum", orderNum)
					.set("sendContent", request.getBizContent())
					.set("returnContent", response.getBody())
					.set("payMethod", OrderCode.OrderPayMethod.ALIPAY)
					.set("flag", 8).save();
					//根据response中的结果继续业务逻辑处理
					if(response.isSuccess()){
						if ("TRADE_SUCCESS".equals(response.getTradeStatus())||"TRADE_FINISHED".equals(response.getTradeStatus())) {
							try {
								//根据订单号和用户id更改order表的订单状态
								
								order.set("paytype", OrderCode.OrderPayTypes.ALIPAY)
									.set("payState", OrderCode.OrderPayState.HAD_PAY)
									.set("orderState",  OrderCode.OrderLogType.PAY)
									.set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
								if(!order.update()){
									throw new Exception("更改订单失败");
								}
								//根据订单号和用户id记录订单日志
								OrderGLog log = new OrderGLog();
								log.set("orderNum", orderNum)
									.set("type", OrderCode.OrderLogType.PAY)
									.set("user", order.get("userid"))
									.set("action", OrderCode.OrderLogType.PAY_ACTION_WEIXIN)
									.set("content", OrderCode.OrderLogType.PAY_CONTECT);
								if(!log.save()){
									throw new Exception("日志记录失败");
								}
								orderGMoneyStateUpdateAndGive(order,user,1,"购买商品");
								new GroupbuyingService2().dealTeamBuy(order);
								//查询订单表有没有该商品， 分辨是否开团， 是否是团长      团队序号         
//								order = dealTeamOrder(order);   //TODO
//								if(!order.update()){
//									throw new Exception("更改订单失败");
//								}
								return 1;
							} catch (Exception e) { 
								e.printStackTrace();
								logger.info("团购订单支付宝结果查询失败>>>>>>>>>>>>>>>支付宝积分，惠券更新失败");
								return 2;
							}
						}
					}else {
						logger.info("团购订单支付宝结果查询失败");
						return 2;
					}
					
				} catch (AlipayApiException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					logger.info("团购订单支付宝结果查询失败");
					return 2;
				}
			}else {
	    		return 2;
			}
		}else if(order.getInt("payState")==OrderCode.OrderPayState.HAD_PAY){
			try {
				orderGMoneyStateUpdateAndGive(order,user,1,"购买商品");
				if ( order.getInt("paytype") == OrderCode.OrderPayTypes.MONEY){
					new GroupbuyingService2().dealTeamBuy(order);
				}
				return 1;
			} catch (Exception e) {
	    		throw new Exception("更新记录失败");
			}
			
		}
		return 2;
		
	}
	/**
	 * 1.查询该商品有无团购(需要在形成订单前做  判断缓存有无序号缓存，如果没有   做开团资格校验)
	 * 	1.1 有	查询缓存，删除缓存，序号+1 存入缓存并设置订单序号
	 * 			1.1.1 查询商品信息，是否是免单团购
	 * 				1.1.1.1  是，查询每几人免单，免单几人，
	 * 	1.2 无	设置缓存，设置序号1
	 */
	@Before(Tx.class)
	public OrderG dealTeamOrder(OrderG order) {  
		
		int id = order.getInt("goodsid");
		//团购免单
		Goods good =  Goods.me().findById(id);
		//是普通团购还是免单团
		if(good.getInt("gbmethod")==GroupCode.gbmethod.FREE){
			//如果是免单团购
			//团队人数
			int gbSize = good.getInt("gbperson");
			System.out.println(">>>>>>>>>>>>>>>>>>>团队规定大小："+gbSize);
			String certpath = PathKit.getRootClassPath()+"/"+PropKit.get("weixinpay.open.cert");
			String certpassword = PropKit.get("weixinpay.mch_id");
			//是否开团 
			Record record = Db.findFirst("SELECT id as counts FROM t_bus_order_gb WHERE payState=? AND goodsid=? AND orderNum!=? ",OrderCode.OrderPayState.HAD_PAY,id,order.getStr("orderNum"));
//			Integer count = teamCache.get("team"+id);
			System.out.println("是否开团？》》》》》》》》》》"+(record==null));
			Integer count = null;
			if(record == null ){
				//未开团
				count = 1;
				//设置缓存
				teamCache.set("team"+id, count);
			}else{
				//已开团
				//操作缓存中大团号必须是单一线程
				synchronized (GroupbuyingService.class) {
					count = teamCache.get("team"+id);
					//序号+1
					count++;
					//更新 
					teamCache.set("team"+id,count);
				}
				System.out.println(">>>>>>>>>>>>>>>>>>>序号:"+count);
				//优先剔除团中团免单
				//是否有团中团号
				String teamNum = order.getStr("teamNum");
				System.out.println(">>>>>>>>>>>>>>>>>>>团队号："+teamNum);
				//判断是否是团长
				if(order.getInt("isLeader")!=GroupCode.isLeader.LEADER){
					//不是团长 开团中团
					if(teamNum != null){
						int goodid = good.getInt("id");
						int gbsize = gbSize-1;
						System.out.println("团队号:"+teamNum);
						//找出团长，是否已免单
						String sql = "SELECT * FROM t_bus_order_gb WHERE goodsid=? AND teamNum=? AND isFree=0 ";
						Record recss = Db.findFirst(sql+" AND payState=? AND isLeader=? ",goodid, teamNum,OrderCode.OrderPayState.HAD_PAY,GroupCode.isLeader.LEADER);
						//该团已支付的人数，不包含团长
						List<Record> list = Db.find(sql+" AND payState=? AND  isLeader=? ",goodid, teamNum, OrderCode.OrderPayState.HAD_PAY,GroupCode.isLeader.NOTLEADER);
						String num = null;
						
						System.out.println("团中团团长订单:"+recss);
						//团长已经免单
						if(recss==null){
							if(list.size()==gbsize){
								//团长  因为满员  -----  免单
								num = indexOutOfGBsize(gbSize);
								if(num!=null){
									//设置团号 送积分 
									teamNum = num;
									order.set("teamNum", teamNum);
									giveSppointByTeamNum(order);
								}
							}else{
								//团长  因为 大团顺序免单  ---免单
								num = indexOutOfGBsize(gbSize);
								if(num!=null){
									//设置团号 送积分 
									teamNum = num;
									order.set("teamNum", null);
									giveSppointByTeamNum(order);
								}
							}
						}else{
							System.out.println("目前团队队员人数:"+list.size());
							System.out.println("团队最大队员人数:"+gbsize);
							if(list.size()>gbsize){
								//大于 
								num = indexOutOfGBsize(gbSize);
								if(num!=null){
									//设置团号 送积分  
									teamNum = num;
									order.set("teamNum", teamNum);
									giveSppointByTeamNum(order);
								}
							}else if(list.size()==gbsize){
								//找出团长，退款免单，                       送积分
								OrderG orderfree= OrderG.me().findFirst(sql+" AND isLeader=? ",goodid, teamNum,GroupCode.isLeader.LEADER);
								System.out.println("查询团长订单:"+orderfree);
								if(orderfree !=null){
									System.out.println("团长订单不为空");
									orderfree.set("isFree", GroupCode.isFree.NEEDFREE);
									//退款
									if(orderfree.update()){
										System.out.println("团长订单修改为待退款");
										//如果已更改为需免单，那么执行退款，并更改isFree状态以及记录t_bus_order_gb_log日志
										int paytype = orderfree.getInt("paytype");
										System.out.println("支付方式:"+paytype);
										if(paytype==OrderCode.OrderPayMethod.BALANCE){
											//付款方式为余额的退款
											System.out.println(">>>>>>>>>>>团中团：付款方式为余额的退款<<<<<<<<<<<<<<");
										}else if(paytype==OrderCode.OrderPayMethod.WEIXIN){
											//付款方式为微信的退款
											System.out.println(">>>>>>>>>>>团中团：付款方式为微信的退款<<<<<<<<<<<<<<");
											System.out.println(">>>>>>>>>>>付款方式为   微信   的退款<<<<<<<<<<<<<<");
											//付款方式为微信的退款
											String orderNum = orderfree.getStr("orderNum");
											String out_refund_no = "TT"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
											String total_fee = String.valueOf(Double.valueOf(DoubleKit.mul(orderfree.getDouble("amount"),100)).intValue()).toString();
											//向微信发起退款请求
											RefOrderReqData reOrderReqData = new RefOrderReqData(orderNum,out_refund_no,total_fee,total_fee, "团中团免单退款");
											RefOrderResData reOrderRspData = null;
											try {
												reOrderRspData = (RefOrderResData)UtilKit.getObjectFromXML(new HttpsRequest(certpath,certpassword).post(PropKit.get("weixinpay.orderrefund"), reOrderReqData), RefOrderResData.class);
											}catch(Exception e){  
												//发送退款请求失败
												Record re = new Record();
												re.set("orderNum", orderfree.getStr("orderNum"))
												  .set("refundNum",out_refund_no)
												  .set("type",GroupCode.exceptionType.GB_WX_SEND_REQ_FAILED)
												  .set("user",orderfree.getInt("userid"))
												  .set("action",GroupCode.exceptionType.GB_WX_SEND_REQ_FAILED_ACTION_TEAM)
												  .set("content",GroupCode.exceptionType.GB_WX_SEND_REQ_FAILED_CONTENT_TEAM);
												if(!Db.save("t_bus_order_exception_log", re)){
													logger.error("微信退款异常，订单号："+orderfree.getStr("orderNum"));
												}
											}
											//预支付完成
											if(reOrderRspData!=null){
												System.out.println("Response....:"+reOrderReqData);
												//保存接口请求记录
												String sendContent = UtilKit.getXMLFromObject(reOrderReqData);
												String returnContent = UtilKit.getXMLFromObject(reOrderRspData);
												new OrderPayAPIRecord().set("orderNum", orderNum)
													.set("sendContent", sendContent)
													.set("returnContent", returnContent)
													.set("payMethod", paytype)
													.set("flag", 4)
													.save();
												if(reOrderRspData.getReturn_code().equals("SUCCESS")&&reOrderRspData.getResult_code().equals("SUCCESS")){
													//更新订单免单退款状态为退款中。。。
													if(!orderfree.set("isFree", GroupCode.isFree.BACKING).update()){
														//更改订单为   退款中 状态失败 
														Record re = new Record();
														re.set("orderNum", orderfree.getStr("orderNum"))
														  .set("type",GroupCode.exceptionType.UPDATE_GB_REFUNDING_FAILED)
														  .set("user",orderfree.getInt("userid"))
														  .set("action",GroupCode.exceptionType.UPDATE_GBFREEPERSON_FAILED_ACTION_TEAM)
														  .set("content",GroupCode.exceptionType.UPDATE_GB_REFUNDING_FAILED_CONTENT_TEAM);
														if(!Db.save("t_bus_order_exception_log", re)){
															logger.error("需要免单异常，订单号："+orderfree.getStr("orderNum"));
														}
													}
												}
											}
											
										}else if(paytype==OrderCode.OrderPayMethod.ALIPAY){
											System.out.println("进入团中团支付宝退款");
											//支付宝
											String gateway=PropKit.get("applipay.url");
											String app_id=PropKit.get("appalipay.partner");
											String privateKey=PropKit.get("appalipay.privateKey");
											String alipayPublicKey=PropKit.get("appalipay.alipayPublicKey");
											String charset=PropKit.get("applipay.charset");
											String sign_type=PropKit.get("applipay.signType");
											String app_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.appCertPublicKey");
											String alipay_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayCertPublicKey");
											String alipay_root_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayRootCert");
											String alipay_notify_url =PropKit.get("appalipay.goodsOrderNotifyUrl");
											//构造client
											CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
											certAlipayRequest.setServerUrl(gateway);
											certAlipayRequest.setAppId(app_id);
											certAlipayRequest.setPrivateKey(privateKey);
											certAlipayRequest.setFormat("json");
											certAlipayRequest.setCharset(charset);
											certAlipayRequest.setSignType(sign_type);
											certAlipayRequest.setCertPath(app_cert_path);
											certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
											certAlipayRequest.setRootCertPath(alipay_root_cert_path);
											String orderNum=orderfree.getStr("orderNum");
											String total_fee = String.valueOf(Double.valueOf(orderfree.getDouble("amount")));
											DefaultAlipayClient alipayClient;
											try {
												alipayClient = new DefaultAlipayClient(certAlipayRequest);
												AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();//创建API对应的request类
												request.setBizContent("{" +
												"    \"out_trade_no\":\""+orderNum+"\"," +
												"    \"refund_reason\":\"团中团免单退款\"," +
												"    \"refund_amount\":\""+total_fee+"\"" +
												
												"  }");//设置业务参数
												AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);//通过alipayClient调用API，获得对应的response类
												System.out.println("支付宝退款请求响应："+response.getBody());
												if (response.isSuccess()) {//请求成功
													System.out.println("支付宝退款请求成功");
													//保存接口请求记录
													new OrderPayAPIRecord().set("orderNum", orderNum)
														.set("sendContent", request.getBizContent())
														.set("returnContent", response.getBody())
														.set("payMethod", paytype)
														.set("flag", 4)
														.save();
													if("Success".equals(response.getMsg())){
														System.out.println("支付宝退款成功");
														//更新订单免单退款状态为退款中。。。
														if(!orderfree.set("isFree", GroupCode.isFree.BACKED).update()){
															//更改订单为   退款中 状态失败 
															Record re = new Record();
															re.set("orderNum", orderfree.getStr("orderNum"))
															  .set("type",GroupCode.exceptionType.UPDATE_GB_REFUND_FAILED)
															  .set("user",orderfree.getInt("userid"))
															  .set("action",GroupCode.exceptionType.UPDATE_GBFREEPERSON_FAILED_ACTION_TEAM)
															  .set("content",GroupCode.exceptionType.UPDATE_GB_REFUND_FAILED_CONTENT_TEAM);
															if(!Db.save("t_bus_order_exception_log", re)){
																logger.error("支付宝需要免单异常，订单号："+orderfree.getStr("orderNum"));
															}
														}
													}
												}else {
													//发送退款请求失败
													Record re = new Record();
													re.set("orderNum", orderfree.getStr("orderNum"))
													  .set("type",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED)
													  .set("user",orderfree.getInt("userid"))
													  .set("action",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED_ACTION_TEAM)
													  .set("content",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED_CONTENT_TEAM);
													if(!Db.save("t_bus_order_exception_log", re)){
														logger.error("支付宝退款异常，订单号："+orderfree.getStr("orderNum"));
													}
												}
											} catch (AlipayApiException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
												//发送退款请求失败
												Record re = new Record();
												re.set("orderNum", orderfree.getStr("orderNum"))
												  .set("type",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED)
												  .set("user",orderfree.getInt("userid"))
												  .set("action",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED_ACTION_TEAM)
												  .set("content",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED_CONTENT_TEAM);
												if(!Db.save("t_bus_order_exception_log", re)){
													logger.error("支付宝团中团退款请求异常，订单号："+orderfree.getStr("orderNum"));
												}
											}
											
										}
										giveSppointByTeamNum(order);
									}else{
										System.out.println("团中团团长订单更改为待退款 失败");
										//更改订单失败状态失败 
										Record re = new Record();
										re.set("orderNum", orderfree.getStr("orderNum"))
										  .set("type",GroupCode.exceptionType.UPDATE_GBFREEPERSON_FAILED)
										  .set("user",orderfree.getInt("userid"))
										  .set("action",GroupCode.exceptionType.UPDATE_GBFREEPERSON_FAILED_ACTION_TEAM)
										  .set("content",GroupCode.exceptionType.UPDATE_GBFREEPERSON_FAILED_CONTENT_TEAM);
										if(!Db.save("t_bus_order_exception_log", re)){
											logger.error("团中团需要免单异常，订单号："+orderfree.getStr("orderNum"));
										}
									}
								}
							}else{
								System.out.println("目前人数不满足退款");
								//小于 送积分
								giveSppointByTeamNum(order);
							}
						}
						
						
					}
				}
				
				//查询免单位置   TODO
				Integer num = null;
				synchronized (order) {
					num = teamCache.get("free"+id);
					if(num == null){
						num = 0;
					}
					if((count-num)>=gbSize){
						teamCache.set("free"+id,num+gbSize);
					}
				}
				System.out.println(">>>>>>>>>>>>>>>>>>>免单位置num:"+num);
				//需要大团免单退款
				if((count-num)>=gbSize){
					System.out.println(">>>>>>>>>>>>>>>>>>>序号-免单位置:"+(count-num));
					//团队免单人数
					int gbFree = good.getInt("gbfreeperson");
					System.out.println(">>>>>>>>>>>>>>>>>>>免单人数:"+gbFree);
					//查询数据库,查询出该商品未免单，订单状态未退款，的订单
					String sql = "SELECT * FROM t_bus_order_gb WHERE isFree=0 AND paystate=2 AND goodsid=? AND tuistate=0  ORDER BY buyNum ";
					List<OrderG> orderList = OrderG.me().find(sql, id);
					
					if(orderList.size()>0&&orderList!=null){
						//需要免单的订单
						for(int i=0;i<gbFree;i++){
							OrderG orderfree = orderList.get(i).set("isFree", GroupCode.isFree.NEEDFREE);
							if(orderfree.update()){
								
								//如果已更改为需免单，那么执行退款，并更改isFree状态以及记录t_bus_order_gb_log日志
								int paytype = orderfree.getInt("paytype");
								System.out.println(">>>>>>>>>>>>>>>>>>>paytype:"+paytype);
								if(paytype==OrderCode.OrderPayMethod.BALANCE){
									//付款方式为余额的退款
									System.out.println(">>>>>>>>>>>付款方式为   郑大   的退款<<<<<<<<<<<<<<");
								}else if(paytype==OrderCode.OrderPayMethod.WEIXIN){
									System.out.println(">>>>>>>>>>>付款方式为   微信   的退款<<<<<<<<<<<<<<");
									//付款方式为微信的退款
									String orderNum = orderfree.getStr("orderNum");
									String out_refund_no = "TT"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
									String total_fee = String.valueOf(Double.valueOf(DoubleKit.mul(orderfree.getDouble("amount"),100)).intValue()).toString();
									//向微信发起退款请求
									RefOrderReqData reOrderReqData = new RefOrderReqData(orderNum,out_refund_no,total_fee,total_fee, "免单退款");
									RefOrderResData reOrderRspData = null;
									try {
										String post = new HttpsRequest(certpath,certpassword).post(PropKit.get("weixinpay.orderrefund"), reOrderReqData);
										System.out.println("<<<<<<<<<<<<<:"+post+":>>>>>>>>>>>>>>>");
										reOrderRspData = (RefOrderResData)UtilKit.getObjectFromXML(post, RefOrderResData.class);
									}catch(Exception e){
										e.printStackTrace();
										//发送退款请求失败
										Record re = new Record();
										re.set("orderNum", orderfree.getStr("orderNum"))
										  .set("refundNum",out_refund_no)
										  .set("type",GroupCode.exceptionType.GB_WX_SEND_REQ_FAILED)
										  .set("user",orderfree.getInt("userid"))
										  .set("action",GroupCode.exceptionType.GB_WX_SEND_REQ_FAILED_ACTION)
										  .set("content",GroupCode.exceptionType.GB_WX_SEND_REQ_FAILED_CONTENT);
										if(!Db.save("t_bus_order_exception_log", re)){
											logger.error("微信退款异常，订单号："+orderfree.getStr("orderNum"));
										}
									}
									//预支付完成
									if(reOrderRspData!=null){
										System.out.println("Response....:"+reOrderReqData);
										//保存接口请求记录
										String sendContent = UtilKit.getXMLFromObject(reOrderReqData);
										String returnContent = UtilKit.getXMLFromObject(reOrderRspData);
										new OrderPayAPIRecord().set("orderNum", orderNum)
											.set("sendContent", sendContent)
											.set("returnContent", returnContent)
											.set("payMethod", paytype)
											.set("flag", 4)
											.save();
										if(reOrderRspData.getReturn_code().equals("SUCCESS")&&reOrderRspData.getResult_code().equals("SUCCESS")){
											//更新订单免单退款状态为退款中。。。
											if(!orderfree.set("isFree", GroupCode.isFree.BACKING).update()){
												//更改订单为   退款中 状态失败 
												Record re = new Record();
												re.set("orderNum", orderfree.getStr("orderNum"))
												  .set("type",GroupCode.exceptionType.UPDATE_GB_REFUNDING_FAILED)
												  .set("user",orderfree.getInt("userid"))
												  .set("action",GroupCode.exceptionType.UPDATE_GBFREEPERSON_FAILED_ACTION)
												  .set("content",GroupCode.exceptionType.UPDATE_GB_REFUNDING_FAILED_CONTENT);
												if(!Db.save("t_bus_order_exception_log", re)){
													logger.error("需要免单异常，订单号："+orderfree.getStr("orderNum"));
												}
											}
										}
									}
									
								}else if(paytype==OrderCode.OrderPayMethod.ALIPAY){
									System.out.println("进入大团支付宝退款");
									//支付宝
									String gateway=PropKit.get("applipay.url");
									String app_id=PropKit.get("appalipay.partner");
									String privateKey=PropKit.get("appalipay.privateKey");
									String alipayPublicKey=PropKit.get("appalipay.alipayPublicKey");
									String charset=PropKit.get("applipay.charset");
									String sign_type=PropKit.get("applipay.signType");
									String app_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.appCertPublicKey");
									String alipay_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayCertPublicKey");
									String alipay_root_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayRootCert");
									String alipay_notify_url =PropKit.get("appalipay.goodsOrderNotifyUrl");
									//构造client
									CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
									certAlipayRequest.setServerUrl(gateway);
									certAlipayRequest.setAppId(app_id);
									certAlipayRequest.setPrivateKey(privateKey);
									certAlipayRequest.setFormat("json");
									certAlipayRequest.setCharset(charset);
									certAlipayRequest.setSignType(sign_type);
									certAlipayRequest.setCertPath(app_cert_path);
									certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
									certAlipayRequest.setRootCertPath(alipay_root_cert_path);
									String orderNum=orderfree.getStr("orderNum");
									String out_refund_no = "TT"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
									String total_fee = String.valueOf(Double.valueOf(orderfree.getDouble("amount")));
									DefaultAlipayClient alipayClient;
									try {
										alipayClient = new DefaultAlipayClient(certAlipayRequest);
										AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();//创建API对应的request类
										request.setBizContent("{" +
										"    \"out_trade_no\":\""+orderNum+"\"," +
										"    \"refund_reason\":\"免单退款\"," +
										"    \"refund_amount\":\""+total_fee+"\"" +
										
										"  }");//设置业务参数
										AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);//通过alipayClient调用API，获得对应的response类
										System.out.print("支付宝退款请求响应："+response.getBody());
										if (response.isSuccess()) {//请求成功
											System.out.println("大团支付宝退款请求成功");
											//保存接口请求记录
											new OrderPayAPIRecord().set("orderNum", orderNum)
												.set("sendContent", request.getBizContent())
												.set("returnContent", response.getBody())
												.set("payMethod", paytype)
												.set("flag", 4)
												.save();
											if("Success".equals(response.getMsg())){
												System.out.println("大团支付宝退款成功");
												//更新订单免单退款状态为退款中。。。
												if(!orderfree.set("isFree", GroupCode.isFree.BACKED).update()){
													//更改订单为   退款中 状态失败 
													Record re = new Record();
													re.set("orderNum", orderfree.getStr("orderNum"))
													  .set("type",GroupCode.exceptionType.UPDATE_GB_REFUND_FAILED)
													  .set("user",orderfree.getInt("userid"))
													  .set("action",GroupCode.exceptionType.UPDATE_GBFREEPERSON_FAILED_ACTION)
													  .set("content",GroupCode.exceptionType.UPDATE_GB_REFUND_FAILED_CONTENT);
													if(!Db.save("t_bus_order_exception_log", re)){
														logger.error("支付宝需要免单异常，订单号："+orderfree.getStr("orderNum"));
													}
												}
											}
										}else {
											//发送退款请求失败
											Record re = new Record();
											re.set("orderNum", orderfree.getStr("orderNum"))
											  .set("refundNum",out_refund_no)
											  .set("type",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED)
											  .set("user",orderfree.getInt("userid"))
											  .set("action",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED_ACTION)
											  .set("content",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED_CONTENT);
											if(!Db.save("t_bus_order_exception_log", re)){
												logger.error("支付宝退款异常，订单号："+orderfree.getStr("orderNum"));
											}
										}
									} catch (AlipayApiException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
										//发送退款请求失败
										Record re = new Record();
										re.set("orderNum", orderfree.getStr("orderNum"))
										  .set("refundNum",out_refund_no)
										  .set("type",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED)
										  .set("user",orderfree.getInt("userid"))
										  .set("action",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED_ACTION)
										  .set("content",GroupCode.exceptionType.GB_ZFB_SEND_REQ_FAILED_CONTENT);
										if(!Db.save("t_bus_order_exception_log", re)){
											logger.error("支付宝大团退款异常，订单号："+orderfree.getStr("orderNum"));
										}
									}
								}
							}else{
								//更改订单失败状态失败 
								Record re = new Record();
								re.set("orderNum", orderfree.getStr("orderNum"))
								  .set("type",GroupCode.exceptionType.UPDATE_GBFREEPERSON_FAILED)
								  .set("user",orderfree.getInt("userid"))
								  .set("action",GroupCode.exceptionType.UPDATE_GBFREEPERSON_FAILED_ACTION)
								  .set("content",GroupCode.exceptionType.UPDATE_GBFREEPERSON_FAILED_CONTENT);
								if(!Db.save("t_bus_order_exception_log", re)){
									logger.error("需要免单异常，订单号："+orderfree.getStr("orderNum"));
								}
							}
						}
					}else{
						//查询失败 
						logger.error("查询团队异常---");
					}
//					更新免单位置  TODO
//					teamCache.set("free"+id,num+gbSize);
				}
				
			}
			//设置  大团号
			order.set("buyNum", count);
			return order;
		}else{
			//如果普通团购，无需免单逻辑
			return order;
		}
	}
	/**
	 * 赠送邀请积分
	 * @param order
	 */
	public void giveSppointByTeamNum(OrderG order) {
		String sql = "SELECT tu.id,tu.sppoint FROM t_bus_order_gb tg "
				+ "LEFT JOIN t_bus_user tu ON tg.userid=tu.id "
				+ "WHERE tg.teamNum=? AND isLeader=? ";
		Record re = Db.findFirst(sql,order.getStr("teamNum"),GroupCode.isLeader.LEADER);
		if(re!=null){
			Double sppoint = re.getDouble("sppoint");
			//准备数据
			//奖励积分
			Double sppoints = 0.00;
			try {
				sppoints = SysConfig.getGroupSppoint();
			} catch (Exception e) {
				
			}
			Double newsppoint = DoubleKit.add(sppoint, sppoints);
			Db.update("UPDATE t_bus_user SET sppoint=? WHERE id=?",newsppoint,re.getInt("id"));
			
			Record record = new Record();
			record.set("type", 1)
				  .set("flag", 11)
				  .set("fromOrderNum", order.getStr("orderNum"))
				  .set("orderMoney", order.getDouble("amount"))
				  .set("userid", order.getInt("userid"))
				  .set("sppoint", sppoints)
				  .set("sppointHistory", sppoint)
				  .set("describe", "团购邀请赠送积分")
				  .set("createDate", new Date());
			Db.save("t_bus_user_value_log", record);	  
		}
	}

	/**
	 * 当团队人数超员时的处理
	 * @param gbSize
	 */
	private String indexOutOfGBsize(int gbSize) {
		//找出其他  未退款，已支付的团中团团长，按支付日期升序
		String sql = "SELECT *,COUNT(*) AS counts  FROM t_bus_order_gb WHERE payState=2 AND tuistate=0 AND teamNum is not null  GROUP BY teamNum ORDER BY payDate";
		List<Record> list = Db.find(sql);
		if(list!=null && list.size()>0){
			for(Record re : list){
				//如果该团未解散  并且  未满员  
				if(re.getInt("isFree")==0&&re.getInt("counts")<gbSize){
					return re.getStr("teamNum");
				}
			}
		}
		return null;
	}

	/**
	 * 根据兑换单号查询出订单列表<br/>
	 * 排除已删除的订单
	 */
	public List<OrderG> getOrderGListByMergerOrderNum(String orderNum){
		String sql = "SELECT * FROM t_bus_order_gb WHERE orderNum=?  AND orderState!=?";
		return OrderG.me().find(sql,orderNum,OrderCode.OrderState.DELETE);
	}
	/**
	 * 有回调普通订单的支付
	 * @param order 订单
	 * @param user	用户
	 * @param action  微信  or  支付宝
	 * @param type	1 增加 2减少
	 * @param describe 用途描述
	 * @throws Exception 
	 * @Return  1 成功  2 更改订单失败 3 用户券信息更新失败  4 减少库存失败 5记录日志失败  7 更改用户等级失败  8 记录等级变更失败
	 */
	@Before(Tx.class)
	public void orderGMoneyStateUpdateAndGive(OrderG order, User user, int type, String describe) throws Exception {
		
		//获取订单号
		String  orderNum = order.getStr("orderNum");
		//规格id
		int  userid = user.getInt("id");
		//查询初始化信息
		Record user1 = Db.findById("t_bus_user", userid);
		//订单消费金额
		Double money = order.getDouble("amount");
				
		//目前消费登记
		Double totalMoney=user.getDouble("totalMoney");
		Double newTotalMoney=DoubleKit.add(totalMoney, money);
		if(Db.update("UPDATE t_bus_user SET totalMoney = ? WHERE id=?",newTotalMoney,userid)!=1){
			throw new Exception("总消费金额添加失败");
		}
		//  更改等级
		//目前消费登记
		int level =  user1.getInt("taici");
		if(level!=0){
			//查询消费等级的下一等级对应积分
			Record levels = Db.findFirst("SELECT `toMoney` FROM t_bus_user_level_set WHERE `levelCode`=?",level+1);
			if(levels!=null){
				Double levelnum = levels.getDouble("toMoney");
				
				//历史消费总金额
				Double moneySum =  orderservice.moneyChage(userid);
				
				if(levelnum.compareTo(moneySum)!=1){
					//更改用户表等级
					if(Db.update("UPDATE t_bus_user SET taici = ? WHERE id=?",level+1,userid)==1){
						//如果变化  t_bus_user_level_log   记录等级变化日志
						if(Db.update("INSERT INTO t_bus_user_level_log(userid,fromLevel,toLevel,flag,createDate) VALUES(?,?,?,?,?)", userid,level,level+1,1,new Date())!=1){
							throw new Exception("记录等级变更失败");
						}
					}else{
						throw new Exception("更改用户等级失败");
					}
					
				}
			}else{
				
				System.out.println("满级了");
			}
			
		}
	}

	
	/**
	 * 查询未满员，未失效的团中团展示数据
	 * @param id
	 * @return
	 */
	public List<Record> teamNum(String teamNum,String id){
		String sql = "SELECT tu.avator FROM t_bus_order_gb tg "
				+ "LEFT JOIN t_bus_user tu ON tg.userid=tu.id WHERE tg.payState=? AND tg.goodsid=? AND tg.teamNum=? ORDER BY tg.teamNum ";
		return Db.find(sql,OrderCode.OrderPayState.HAD_PAY,id,teamNum);
	}
	/**
	 * 查询未满员，未失效的团中团团长
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Record> teamList(String id,String inviteid) {
		int ivid = Integer.parseInt(inviteid);
		//查找有效团长的订单
		StringBuffer sql = new StringBuffer("SELECT g.*,tu.name,tu.avator,tg.gbperson FROM t_bus_order_gb g "
				+ " LEFT JOIN t_bus_user tu ON g.userid=tu.id "
				+ " LEFT JOIN t_bus_goods tg ON g.goodsid=tg.id  "
				+ " WHERE "
				+ " g.isLeader=? AND g.payState=? AND g.isFree=? AND g.goodsid=? ");
		List<Record> find = null;
		if ( ivid==0 ){
			//查看全部
			find = Db.find(sql.toString(),GroupCode.isLeader.LEADER,OrderCode.OrderPayState.HAD_PAY,0,id);
		}else {
			//查看邀请人所属订单
			sql.append(" AND userid=? ");
			find = Db.find(sql.toString(),GroupCode.isLeader.LEADER,OrderCode.OrderPayState.HAD_PAY,0,id,inviteid);
		}
		if ( find!=null && find.size()>0 ){
			//筛选出团长的团中团
			List<Record> collect = find.stream().map(record -> {
				//从redis中筛选出未满员的团中团订单返回
//				teamNum+teamsize+id 存放该团中团成员订单id
				String teamNum = record.getStr("teamNum");
				String key = teamNum + RedisKey.Key.TEAMSIZE + id;
				List<Integer> list = FastJson.getJson().parse(teamCache.getJedis().get( key ),List.class);
				if ( list!=null && list.size()<record.getInt("gbperson")){
					return record.set("num", list.size());
				}
				return null;
			}).filter(record ->
				record!=null
			).collect(Collectors.toList());
			System.out.println("LLLLLLLLLLLLLLL"+collect.size());
			System.out.println("LLLLLLLLLLLLLLL"+collect);
			//排序
			Collections.sort(collect,new Comparator<Record>() {

				@Override
				public int compare(Record re1, Record re2) {
					int count = re1.getInt("buyNum") - re2.getInt("buyNum");
					if (count>0){
						return 1;
					}else {
						return -1;
					}
				}
			});
			System.out.println("LLLLLLLLLLLLLLL"+collect.size());
			return collect;
		}
		List<Record> lis = new ArrayList<Record>();
		return lis;
//		StringBuffer sql = new StringBuffer();
//		sql.append("SELECT tg.userid,tg.teamnum,tu.name,tu.avator FROM ");
//		sql.append(" (SELECT *,COUNT(*) as counts FROM t_bus_order_gb WHERE payState=? AND teamNum is not null AND goodsid=? GROUP BY teamNum ) tg ");
//		sql.append(" LEFT JOIN t_bus_user tu ON tg.userid=tu.id ");
//		sql.append(" LEFT JOIN t_bus_goods tgg ON tg.goodsid=tgg.id ");
//		sql.append(" WHERE   tg.counts<(tgg.gbperson+1) AND tg.isFree=0 AND tg.payState=? AND tg.tuistate=? ");
//		String teamNum = null;
//		int ivid = Integer.parseInt(inviteid);
//		if(ivid!=0){
//			//判断是否为未满员的团长
//			String sql1 = "SELECT teamNum FROM t_bus_order_gb WHERE payState=? AND tuistate=? AND isFree=0 AND isLeader=? AND userid=? AND goodsid=? ";
//			List<OrderG> orderlist = OrderG.me().find(sql1,OrderCode.OrderPayState.HAD_PAY,OrderCode.OrderTuiState.NO_REFUND,GroupCode.isLeader.LEADER,inviteid,id);
//			if(orderlist!=null&&orderlist.size()>0){
//				//该人员在该商品有有效团
//				for(OrderG order :orderlist){
//					//显示该团未满员
//					teamNum =order.getStr("teamNum");
//					String sql2 = "SELECT * FROM "
//							+ " (SELECT *,COUNT(*) as counts FROM t_bus_order_gb "
//							+ " WHERE payState=? AND  tuistate=?  AND teamNum=? AND  goodsid=?  ) tg "
//							+ " LEFT JOIN t_bus_goods tgg ON tg.goodsid=tgg.id "
//							+ " WHERE  tg.counts<(tgg.gbperson+1)  ";
//					Record rec = Db.findFirst(sql2,OrderCode.OrderPayState.HAD_PAY,OrderCode.OrderTuiState.NO_REFUND,teamNum,id);
//					if(rec!=null){
//						sql.append(" AND tg.teamNum=? ");
//					}
//				}
//			}
//			System.out.println(">>>>>>>>>>>>>>"+sql.toString());
//			System.out.println(">>>>>>>>>>>>"+inviteid+"<<<<");
//			System.out.println(">>>>>>>>>>>>邀请人");
//			sql.append(" ORDER BY tg.payDate ");
//			return Db.find(sql.toString(),OrderCode.OrderPayState.HAD_PAY,id,OrderCode.OrderPayState.HAD_PAY,OrderCode.OrderTuiState.NO_REFUND,teamNum);
//		}else {
//			System.out.println(">>>>>>>>>>>>>>"+sql.toString());
//			System.out.println(">>>>>>>>>>>>"+inviteid+"<<<<");
//			System.out.println(">>>>>>>>>>>>所有人");
//			return Db.find(sql.toString(),OrderCode.OrderPayState.HAD_PAY,id,OrderCode.OrderPayState.HAD_PAY,OrderCode.OrderTuiState.NO_REFUND);
//		}
	}
	/**
	 * 定时更新团购失效订单，更改库存信息
	 */
	@Before(Tx.class)
	public void changeGroup() throws Exception{
		//获取现在时间
		String nowdate = DatetimeKit.getFormatDate("");
		//获取60秒前的时间
		String olddate = DatetimeKit.getIntervalFormatDateb(1000*60,"");
		//查找未付款，非取消的已失效或已删除订单
		String sql = "SELECT to1.* FROM "
				+ " t_bus_order_gb to1 "
				+ " WHERE (to1.orderState=? OR to1.orderState=?) "
				+ " AND to1.expireDate>? AND to1.expireDate<? AND to1.reason is null ";
		List<OrderG> list1 = OrderG.me().find(sql,OrderCode.OrderState.NORMAL,OrderCode.OrderState.DELETE,olddate,nowdate);
		
		System.out.println(list1);
		
		if(list1!=null && list1.size()>0){
			for(OrderG rec : list1){
				OrderGLog orderLog = new OrderGLog();
				orderLog.set("orderNum", rec.getStr("orderNum"))
				.set("type", OrderCode.OrderLogType.EXPIRY)
				.set("user",  rec.getInt("userid"))
				.set("action", OrderCode.OrderLogType.EXPIRY_ACTION)
				.set("content", OrderCode.OrderLogType.EXPIRY_CONTECT);
				if(!orderLog.save()){
					logger.info(">>>>>>>>>团购日志记录失败");
				}
				int goodsid = rec.getInt("goodsid");
				Goods good = Goods.me().findById(goodsid);
				if(good!=null){
					good.set("countnum", rec.getInt("countnum")+1)  ;
					//加库存，操作数据库
					updateDBGoods(good);
				}
			}
		}
		
	}
	/**
	 * 取消团购订单  回滚库存
	 */
	@Before(Tx.class)
	public void cannlGroup(String orderNum,String reson,int id) throws Exception{
		//更改订单状态
		String sql = "UPDATE t_bus_order_gb SET orderState=?,reason=?,expireDate=? WHERE orderNum=? AND userid=? ";
		if(Db.update(sql,OrderCode.OrderState.NORMAL,reson,new Date(),orderNum,id)!=1){
			throw new RuntimeException("取消订单失败");
		}
		OrderGLog orderLog = new OrderGLog();
		orderLog.set("orderNum", orderNum)
		.set("type", OrderCode.OrderLogType.CANCEL)
		.set("user", id)
		.set("action", OrderCode.OrderLogType.CANCEL_ACTION)
		.set("content", OrderCode.OrderLogType.CANCEL_CONTECT);
		if(orderLog.save()){
			
		}else{
			logger.info(">>>>>>>>>团购日志记录失败");
			throw new Exception("网络繁忙...，请稍后重试");
		}
		sql = "SELECT tg.* FROM "
			+ " t_bus_order_gb to1 "
			+ " LEFT JOIN t_bus_goods tg ON tg.id=to1.goodsid "
			+ " WHERE to1.orderNum=? AND to1.userid=? ";
		//查找
		Goods good= Goods.me().findFirst(sql,orderNum,id);
		if(good!=null){
			good.set("countnum", good.getInt("countnum")+1)  ;
			//加库存，操作数据库
			updateDBGoods(good);
		}else{
			throw new Exception("网络繁忙...请稍后重试");
		}
	}
	
	/**
	 * 查询所有团购商品
	 * @return
	 */
	public List<Record> findGroupBuyGoods() {
		return Db.find("select tg.* "
				+ " ,(SELECT IFNULL(SUM(bol.count),0 ) FROM t_bus_order_gb bo INNER JOIN t_bus_order_list bol ON bo.orderNum=bol.orderNum WHERE bol.goodsid=tg.id AND bo.payState="+OrderCode.OrderPayState.HAD_PAY+") saleCount "
				+ "from t_bus_goods tg where tg.groupbuying=2 and tg.state =2 AND tg.gbendtime > now() AND tg.gbbegintime<= now()  order by createDate DESC");
	}
	
	/**
	 * 分页查询所有团购商品
	 * @return
	 */
	public Page<Record> findGroupBuyGoodsPage(int pageNum,int pageSize) {
		return Db.paginate(pageNum, pageSize, "select tg.* "
				+ " ,(SELECT IFNULL(SUM(bol.count),0 ) FROM t_bus_order_gb bo INNER JOIN t_bus_order_list bol ON bo.orderNum=bol.orderNum WHERE bol.goodsid=tg.id AND bo.payState="+OrderCode.OrderPayState.HAD_PAY+") saleCount  "
				," from t_bus_goods tg where tg.groupbuying=2 and tg.state =2 AND tg.gbendtime > now() AND tg.gbbegintime<= now()  ORDER BY id DESC ");
	}
	
	/**
	 * 团购订单余额付款
	 * @param user
	 * @param amount
	 * @return 1  成功  2  更改用户余额失败 3记录money变化表失败
	 */
	@Before(Tx.class)
	public int chanegMoney (User user, double amount,String orderNum,OrderG order) throws Exception{
		int userid = user.getInt("id");
		//变化前金额
		Double oldMoney = user.getDouble("money");
			//增加的金额
		Double addMoney = amount;
			//变化后金额
		Double newMoney = DoubleKit.sub(oldMoney, addMoney);
		
		Record re = new Record().set("userid", userid)
				.set("amount", amount)
				.set("type", "2")
				.set("fromOrderNum", orderNum)
				.set("createDate", new Date())
				.set("orderType", OrderCode.MoneyState.GOODORDER)
				.set("nowAmount", newMoney)
				.set("oldAmount", oldMoney)
				.set("describe", "购买团购商品");
		if(Db.update("UPDATE t_bus_user SET money = ? WHERE id = ?", newMoney,userid)==1){
			if(Db.save("t_bus_user_money", re)){
				if (order.set("orderState", OrderCode.OrderPayState.HAD_PAY).set("payState", OrderCode.OrderPayState.HAD_PAY).set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).update()) {
					if(Db.update("INSERT INTO t_bus_order_log(orderNum,type,user,action,content) VALUES(?,?,?,?,?)",orderNum,OrderCode.OrderLogType.PAY,"用户",OrderCode.OrderLogType.PAY_ACTION,"订单支付成功，等待系统确认")==1){
						return 1;
					}
					throw new Exception("订单日志记录失败");
				}
				throw new RuntimeException("更改订单状态失败"); 
			}
			throw new RuntimeException("记录money变化表失败"); 
		}
		throw new RuntimeException("更改用户余额失败"); 
	}
	/**
	 * 邀请成团
	 */
	public void beTeam(int orderid,User user) {
		//开启redis的list
		List<Integer> list = new ArrayList<Integer>();
		//生成团中团编号
		String  teamNum = DatetimeKit.getFormatDate("yyyyMMddHHmmss")+user.getInt("id");
		OrderG order = OrderG.me().findById(orderid);
		
		if ( order !=null){
			order.set("teamNum", teamNum).set("isLeader", GroupCode.isLeader.LEADER).update();
			teamCache.getJedis().set(teamNum+RedisKey.Key.TEAMSIZE+order.getInt("goodsid"),JsonKit.toJson(list));
			System.out.println("邀请成团：团队号:"+teamNum+"   orderid:"+orderid+"--teamNum+RedisKey.Key.TEAMSIZE+goodsid"+list);
		}
	}
	/**
	 * 开团检查是否需要下单
	 * @param user
	 */
	public int check(User user,String id) {
		// 筛选出  是否有已支付，有效的  拼团订单
		String sql1 = "SELECT * FROM t_bus_order_gb "
				+ " WHERE payState=? AND goodsid=? AND  isFree=? AND isLeader!=? AND userid=? ORDER BY payDate ";
		List<OrderG> find = OrderG.me().find(sql1,OrderCode.OrderPayState.HAD_PAY,id,0,GroupCode.isLeader.LEADER,user.getInt("id"));
		if ( find!=null && find.size()>0 ){
			// 如果有   执行beTeam   返回特殊字段
			beTeam(find.get(0).getInt("id"),user);
			return 1;
		} else {
			// 如果没有，执行开团
			return -1;
		}
		
	}
	
}
